package com.itheima.web.controller.front;

import com.github.pagehelper.PageInfo;
import com.itheima.core.BaseServlet;
import com.itheima.domain.front.Member;
import com.itheima.service.front.MemberService;
import com.itheima.service.front.impl.MemberServiceImpl;
import com.itheima.utils.BeanUtil;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.crypto.Data;

@WebServlet("/front/member/*")
public class MemberServlet extends BaseServlet {

    private MemberService memberService = new MemberServiceImpl();

    public String list(HttpServletRequest request , HttpServletResponse response) throws Exception{
        String pageNum = request.getParameter("pageNum");
        String pageSize = request.getParameter("pageSize");
        if (StringUtils.isBlank(pageNum)){
            pageNum  = "1";
        }
        if (StringUtils.isBlank(pageSize)){
            pageSize  = "10";
        }
        PageInfo pageInfo = memberService.queryPage(Integer.parseInt(pageNum), Integer.parseInt(pageSize));

        System.out.println(pageInfo);
        request.setAttribute("page", pageInfo);
        return "WEB-INF/pages/front/member/list.jsp";
    }

    public String toAdd(HttpServletRequest request , HttpServletResponse response) throws Exception{
        return "WEB-INF/pages/front/member/add.jsp";
    }

    public String save(HttpServletRequest request , HttpServletResponse response) throws Exception{
        Member memberInFrom = BeanUtil.fillBean(request, Member.class, "yyyy-mm-dd");

        memberService.add(memberInFrom);

        return "/front/member/list";
    }


    public String toEdit(HttpServletRequest request , HttpServletResponse response) throws Exception{

        Member member = memberService.findById(request.getParameter("id"));
        request.setAttribute("member",member);

        System.out.println(member);
        return "WEB-INF/pages/front/member/update.jsp";
    }

    public String edit(HttpServletRequest request , HttpServletResponse response) throws Exception{

        Member userInFrom = BeanUtil.fillBean(request, Member.class, "yyyy-mm-dd");
        memberService.update(userInFrom);

        return "/front/member/list";
    }

    public String delete(HttpServletRequest request , HttpServletResponse response) throws Exception{

        String[] ids = request.getParameterValues("id");
        memberService.deleteById(ids);

        return "/front/member/list";
    }
}
